package com.recsmile.sgs.net.codec;

import com.recsmile.sgs.commonds.AbstractCommand;
import com.recsmile.sgs.core.Command;
import com.recsmile.sgs.core.Packet;
import com.recsmile.sgs.core.Player;
import com.recsmile.sgs.entity.RequestEnterRoomPacket;
import com.recsmile.sgs.listener.PacketListener;
import com.recsmile.sgs.util.CommandManager;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

/**
 * Created by hanyuanliang on 16/8/24.
 */
public class CommandChannelHandler extends SimpleChannelInboundHandler<Packet>{
    private PacketListener packetListener;

    public CommandChannelHandler(PacketListener packetListener) {
        this.packetListener = packetListener;
    }

    protected void channelRead0(ChannelHandlerContext ctx, Packet msg) throws Exception {
        //System.out.println(msg);

        Command command = CommandManager.newInstance(msg.getClass().getName());
        ((AbstractCommand)command).setPacketListener(packetListener);
        command.handle(ctx,msg);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        ctx.writeAndFlush(new RequestEnterRoomPacket().withPlayer(new Player()));
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        //super.exceptionCaught(ctx, cause);
        cause.printStackTrace();
    }
}
